﻿using NewLife.Log;
using NewLife.RocketMQ;
using NewLife.RocketMQ.Protocol;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace WindowsServiceTscPrint
{
    public class RocketHelpter
    {
        /// <summary>
        /// 消息队 主题topic
        /// </summary>
        static readonly string TOPIC = System.Configuration.ConfigurationManager.AppSettings["topic"];

        /// <summary>
        /// 报告打印机状态，主题topic
        /// </summary>
        static readonly string TOPIC_REPORT = System.Configuration.ConfigurationManager.AppSettings["topic_report_print_state"];

        /// <summary>
        /// 订阅组
        /// </summary>
        static readonly string GROUP = System.Configuration.ConfigurationManager.AppSettings["group"];

        /// <summary>
        ///  RocketMQ地址NameServerAddress
        /// </summary>
        static readonly string NameServerAddress = System.Configuration.ConfigurationManager.AppSettings["NameServerAddress"];

        /// <summary>
        /// RocketMQ发送消息，报告打印机状态，printState打印机状态，1=成功打印，0=打印失败或机器故障
        /// </summary>
        public static void SendMsg(string orderNo, int printState = 0)
        {
            /*
             * 
             * 发送消息格式
 PrintState打印情况，1=印成功，0=打印失败或机器故障
{
	OrderNo:"ASDF4564578FGH",
	BackTime:"2020-8-28 11:23:39",
	PrintState:1
}
             */

            //组，group_order_print
            var mq = new Producer
            {
                //topic_order_list_print
                Topic = TOPIC_REPORT,
                NameServerAddress = NameServerAddress,
                //Topic = "topic_order_list_print",        
                //NameServerAddress = "192.168.1.194:9876",

                // Topic = "topic_order_list_print",
                //NameServerAddress = "39.97.85.123:9876",
                //NameServerAddress = "192.168.1.244:9876",
                //NameServerAddress = "192.168.1.14:9876",
                //Log = XTrace.Log,
            };
            mq.Start();
            var data = new
            {
                OrderNo = orderNo,
                BackTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                PrintState = printState
            };
            string msg = Newtonsoft.Json.JsonConvert.SerializeObject(data);
            NewLife.RocketMQ.Protocol.Message message = new NewLife.RocketMQ.Protocol.Message()
            {
                BodyString = msg,
                Keys = mq.Topic,
                Tags = "TagPrintState",
                Flag = 0,
                WaitStoreMsgOK = true
            };
            var sr = mq.Publish(message);
            //var sr = mq.Publish(msg, "TagA");
            string log = $"发送成功的消息，内容>{msg},MsgId={sr.MsgId},BrokerName= {sr.Queue.BrokerName} ,QueueId={sr.Queue.QueueId},QueueOffset= {sr.QueueOffset}";
            LogHelpter.AddLog(log);
            mq.Dispose();
        }

        static NewLife.RocketMQ.Consumer consumer = null;

        static Func<MessageQueue, MessageExt[], bool> reviceMsgFunc = (q, ms) =>
        {
            string backInfo = $"****批量消息BrokerName={q.BrokerName},QueueId={q.QueueId},收到消息Length={ms.Length}";
            LogHelpter.AddLog(backInfo);
            Console.WriteLine(backInfo);
            //播放订单来了提示音
            PrintHelpter.PlaySoundOrderComming();
            int state = 8;
            string json2 = Newtonsoft.Json.JsonConvert.SerializeObject(ms);
            LogHelpter.AddLog("ms=" + json2);
            foreach (var item in ms.ToList())
            {
               string contentJson = item.Body.ToStr();
               // string contentJson = UTF8Encoding.UTF8.GetString(item.Body);
                string msg = $"消息：MessageId={item.MsgId},key={item.Keys}，产生时间【{item.BornTimestamp.ToDateTime()}】，内容>{contentJson}";
                LogHelpter.AddLog(msg);
                Console.WriteLine(msg);

                //打印机，打印消息
                OrderInfo orderInfo = null;
                try
                {
                    state = PrintHelpter.PrintMsg(contentJson, out orderInfo);
                    if (state == 0)
                    {
                        //打印机没有准备好
                        //consumer.ConsumerInterval = 30;//测试无效果
                        //停止接收消息
                        StopConsumer();
                        //30秒后再启动激活
                        Task.Run(() =>
                        {
                            Thread.Sleep(60 * 1000);
                            ReviceMsg();
                            //Console.ReadLine();
                        });
                    }
                    if (state == 1)
                    {
                        //报告打印消息，只推送成功的打印
                        SendMsg(orderInfo.OrderNo, 1);
                    }
                    LogHelpter.AddLog("消费间隔ConsumerInterval=" + consumer.ConsumerInterval);
                }
                catch (Exception ex)
                {
                    LogHelpter.AddLog("打印异常，" + ex.ToString());
                }
                if (state == 0)
                {
                    break;
                }
                Thread.Sleep(6 * 1000);
            }

            if (state == 1)
            {
                return true;
            }
            else
            {
                return false;
            }
            //返回true表示消息被消费，false消息没有被消费
            //return true;
        };

        /// <summary>
        /// RocketMQ 接收消息
        /// </summary>
        public static void ReviceMsg()
        {
            try
            {

                //测试消费消息
                consumer = new NewLife.RocketMQ.Consumer
                {
                    //Topic = "topic_order_list_print",
                    //Group = "group_order_print",
                    //NameServerAddress = "127.0.0.1:9876",
                    Topic = TOPIC,
                    Group = GROUP,
                    NameServerAddress = NameServerAddress,
                    //FromLastOffset = true,
                    //SkipOverStoredMsgCount = 0,
                    //设置每次推送接收一条消息
                    BatchSize = 1,
                    //Log = NewLife.Log.XTrace.Log,
                };
                consumer.OnConsume = reviceMsgFunc;
                consumer.Start();
                LogHelpter.AddLog("启动接收消息成功");
            }
            catch (Exception ex)
            {
                LogHelpter.AddLog("启动接收异常,"+ex.ToString());
            }
        }

        /// <summary>
        /// 停止接收消息
        /// </summary>
        public static void StopConsumer()
        {
            try
            {
                consumer.OnConsume = null;
                consumer.Dispose();
                LogHelpter.AddLog("停止接收消息成功");
            }
            catch (Exception ex)
            {
                LogHelpter.AddLog("停止接收消息异常，" + ex.ToString());
            }
        }

    }
}
